package com.yutel.multher.reaper.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yutel.multher.reaper.ReaperServer;
import com.yutel.multher.reaper.domain.QueueList;
import com.yutel.multher.reaper.domain.TaskData;
import com.yutel.multher.reaper.listener.OnTaskListener;

public class ParallelTask<T extends TaskData> implements Runnable {
	private static final Logger log = LoggerFactory
			.getLogger(ParallelTask.class);
	private int taskInterval;
	private QueueList<T> queueList;
	private OnTaskListener<T> taskListener;

	public ParallelTask(ReaperServer<T> reaperServer) {
		taskInterval = reaperServer.getTaskInterval();
		queueList = reaperServer.getQueueList();
		taskListener = reaperServer.getOnTaskListener().NewTask();
	}

	@Override
	public void run() {
		while (true) {
			try {
				T t = queueList.poll();
				if (t == null) {
					log.debug("task sleep time:{}", taskInterval);
					Thread.sleep(taskInterval);
				} else {
					taskListener.OnTaskProcess(t);
				}
			} catch (Exception e) {
				log.error("main service error", e);
			}
		}
	}

}
